package project6.voip;

//import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.View; 
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.os.Bundle;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.*;


public class VoipActivity extends Activity {
	
	String FILENAME = "settings.txt";
	DirClient dir;
	String userName;
	String server;
	VoiceCaptureClient vpc;
	VoicePlayerServer vps;
	Thread s, c;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*String link = "ring.mp3";
        MediaPlayer mp = new MediaPlayer();
        try {
			mp.setDataSource(link);
			mp.prepare();
			mp.start();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
        
        
        /*RingtoneManager rtm = new RingtoneManager(this);
        rtm.getRingtone(this, RingtoneManager.getActualDefaultRingtoneUri(this, 1));*/
        setSettings();
        dir = new DirClient(server, 65535);
        
        /*Set Call Alert*/
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Caller!")
    	.setCancelable(true)
    	.setMessage("Do You Want to Answer?")
    	.setPositiveButton( "Yes", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int which) {
                Intent myIntent = new Intent();

                myIntent.setAction(Intent.ACTION_VIEW);

                myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                setContentView(R.layout.call);
                setCall("Need Name");
    		}
    	})
    	.setNegativeButton( "No", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int which) {
    			return;
    		}
    	});
    	//AlertDialog alertCall = builder.create();
    	//end Call Alert Setup
    	
    	/*while(true){
    		//listen for connections
    		
    		//if connection show dialog
    			alertCall.show();
    	}*/
    }//end onCreate
    
    //set the main screen
    private void setMain(){
        setContentView(R.layout.main);
        Button settingsButton =(Button)findViewById(R.id.settingsButton);
        
        settingsButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent();

                myIntent.setAction(Intent.ACTION_VIEW);

                myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                setContentView(R.layout.settings);
                setSettings();
            }        
        });
        
	        
        String[] users = dir.getUsers(userName);
    
        //populate list of users else dislay no results
        if(users != null){
	        ListView userList = (ListView)findViewById(R.id.userList);
	        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, users);
	        userList.setAdapter(adapter);
	        
	        //set event for user click
	        userList.setOnItemClickListener(new OnItemClickListener(){
	        	@Override
	        	public void onItemClick(AdapterView<?> parent, View view,
	                    int position, long id){
	                Intent myIntent = new Intent();
	
	                myIntent.setAction(Intent.ACTION_VIEW);
	
	                myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
	                setCall(((TextView)view).getText().toString());
	        	}
	        });
        }
        
        Button refreshButton =(Button)findViewById(R.id.refreshButton);
        
        refreshButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
            	//update list of users
            	setMain();
            }        
        });
        
        Button exitButton = (Button)findViewById(R.id.exitButton);
        
        exitButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
            	dir.logout(userName, getLocalIpAddress());
            	
            	Intent intent = new Intent(Intent.ACTION_MAIN);
            	intent.addCategory(Intent.CATEGORY_HOME);
            	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            	startActivity(intent);
            	
            }        
        });
        
    }
    
    //set the settings window
    public void setSettings(){
    	setContentView(R.layout.settings);
    	Button saveButton =(Button)findViewById(R.id.saveButton);
    	
        SharedPreferences settings = getSharedPreferences(FILENAME, 0);
        this.userName = settings.getString("user", "guest");
        this.server = settings.getString("server", "lore.cs.purdue.edu");
        
        EditText usernameTextBox = (EditText)findViewById(R.id.usernameTextBox);
        EditText serverTextBox = (EditText)findViewById(R.id.serverTextBox);
        
        usernameTextBox.setText(userName);
        serverTextBox.setText(server);
        
        saveButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent();

                myIntent.setAction(Intent.ACTION_VIEW);

                myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                
                /*Save Info To file*/
                EditText usernameTextBox = (EditText)findViewById(R.id.usernameTextBox);
                EditText serverTextBox = (EditText)findViewById(R.id.serverTextBox);
                
                
                String serverName = serverTextBox.getText().toString();
                String username = usernameTextBox.getText().toString();
                
                if(serverName != null && username != null){
	                //commit to file
                	if(!username.equals(userName)){
                		dir.logout(userName, getLocalIpAddress());
                	}
	                saveSettings(username, serverName);
	                dir.login(userName, getLocalIpAddress());
            	
					//go back to main
					setMain();
                }
            }        
        });
    }//end setSettings
    
    //set call screen
    public void setCall(String name){
    	setContentView(R.layout.call);
    	
    	TextView nameText = (TextView)findViewById(R.id.nameText);
    	nameText.setText(name);
    	
    	Button hangUpButton =(Button)findViewById(R.id.hangUpButton);
        
        hangUpButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
            	
            	/*end connection*/
            	vpc.close();
            	vps.close();
            	try {
					c.join(1);
					s.join(1);
	            	
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            	
                //go back to main
                setMain();
            }        
        });
        
        //start voice server
        try{
        	vps= new VoicePlayerServer(this, 65534);
        	System.out.println("starting voice server");
        	s = new Thread(vps);
        	s.start();
        	System.out.println("voice server started");
        }
        catch(Exception e){
        	System.err.println(e.getMessage());
        	//alert unable to start voice server
        }
        
        //send server request
        try{
        	vpc = new VoiceCaptureClient(dir.getIP(name), 65534);
        	System.out.println("starting vpc");
        	c = new Thread(vpc);
        	c.start();
        	System.out.println("starting vpc thread");
        }
        catch(Exception e){
        	System.out.println(e.getMessage());
        	System.out.println("couldn't connect");
        	//send alert saying couldn't get connection
        	setMain();
        }
        //send call to other user
    }
    
    //make the back button go back to the main window
    @Override
    public void onBackPressed() {
    	setMain();
    }//end onBackPressed
    
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }
    @Override
    protected void onDestroy(){
    	super.onDestroy();
    	dir.logout(userName, getLocalIpAddress());
    }
    @Override//run if application stops
    protected void onStop(){
       super.onStop();
       //if application exits, logout user
       dir.logout(userName, getLocalIpAddress());
    }
    private void saveSettings(String user, String server){
    	this.userName=user;
    	this.server=server;
    	SharedPreferences settings = getSharedPreferences(FILENAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("user", user);
        editor.putString("server", server);
        // Commit the edits!
        editor.commit();
    }
}